{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "copyright"
      },
      "outputs": [],
      "source": [
        "# Copyright 2020 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "title"
      },
      "source": [
        "# Custom training and batch prediction\n",
        "\n",
        "<table align=\"left\">\n",
        "  <td>\n",
        "    <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/official/custom-training-batch-prediction.ipynb\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
        "    </a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/official/custom-training-batch-prediction.ipynb\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
        "      View on GitHub\n",
        "    </a>\n",
        "  </td>\n",
        "</table>\n",
        "<br/><br/><br/>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "overview:custom"
      },
      "source": [
        "## Overview\n",
        "\n",
        "\n",
        "This tutorial demonstrates how to use the Vertex SDK for Python to train and deploy a custom image classification model for batch prediction."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dataset:custom,cifar10,icn"
      },
      "source": [
        "### Dataset\n",
        "\n",
        "The dataset used for this tutorial is the [cifar10 dataset](https://www.tensorflow.org/datasets/catalog/cifar10) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use is built into TensorFlow. The trained model predicts which type of class an image is from ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "objective:custom,training,online_prediction"
      },
      "source": [
        "### Objective\n",
        "\n",
        "In this notebook, you create a custom-trained model from a Python script in a Docker container using the Vertex SDK for Python, and then do a prediction on the deployed model by sending data. Alternatively, you can create custom-trained models using `gcloud` command-line tool, or online using the Cloud Console.\n",
        "\n",
        "The steps performed include:\n",
        "\n",
        "- Create a Vertex AI custom job for training a model.\n",
        "- Train a TensorFlow model.\n",
        "- Make a batch prediction.\n",
        "- Cleanup resources."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "costs"
      },
      "source": [
        "### Costs\n",
        "\n",
        "This tutorial uses billable components of Google Cloud (GCP):\n",
        "\n",
        "* Vertex AI\n",
        "* Cloud Storage\n",
        "\n",
        "Learn about [Vertex AI\n",
        "pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
        "pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
        "Calculator](https://cloud.google.com/products/calculator/)\n",
        "to generate a cost estimate based on your projected usage."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_aip"
      },
      "source": [
        "## Installation\n",
        "\n",
        "Install the latest (preview) version of Vertex SDK for Python."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1fd00fa70a2a"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "# The Google Cloud Notebook product has specific requirements\n",
        "IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
        "\n",
        "# Google Cloud Notebook requires dependencies to be installed with '--user'\n",
        "USER_FLAG = \"\"\n",
        "if IS_GOOGLE_CLOUD_NOTEBOOK:\n",
        "    USER_FLAG = \"--user\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YsxCgt1zlugo"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} --upgrade google-cloud-aiplatform"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_storage"
      },
      "source": [
        "Install the latest GA version of *google-cloud-storage* library as well."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qssss-KSlugo"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} --upgrade google-cloud-storage"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_pillow"
      },
      "source": [
        "Install the *pillow* library for loading images."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vhP4dtWUlugp"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} --upgrade pillow"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_numpy"
      },
      "source": [
        "Install the *numpy* library for manipulation of image data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "80-_pO4olugp"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} --upgrade numpy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "restart"
      },
      "source": [
        "### Restart the kernel\n",
        "\n",
        "Once you've installed everything, you need to restart the notebook kernel so it can find the packages."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bzPxhxS5lugp"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "if not os.getenv(\"IS_TESTING\"):\n",
        "    # Automatically restart kernel after installs\n",
        "    import IPython\n",
        "\n",
        "    app = IPython.Application.instance()\n",
        "    app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "before_you_begin"
      },
      "source": [
        "## Before you begin\n",
        "\n",
        "### Select a GPU runtime\n",
        "\n",
        "**Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select \"Runtime --> Change runtime type > GPU\"**\n",
        "\n",
        "### Set up your Google Cloud project\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
        "\n",
        "2. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
        "\n",
        "3. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
        "\n",
        "4. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
        "\n",
        "5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
        "Cloud SDK uses the right project for all the commands in this notebook.\n",
        "\n",
        "**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "project_id"
      },
      "source": [
        "#### Set your project ID\n",
        "\n",
        "**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_project_id"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "PROJECT_ID = \"\"\n",
        "\n",
        "if not os.getenv(\"IS_TESTING\"):\n",
        "    # Get your Google Cloud project ID from gcloud\n",
        "    shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null\n",
        "    PROJECT_ID = shell_output[0]\n",
        "    print(\"Project ID: \", PROJECT_ID)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "set_project_id"
      },
      "source": [
        "Otherwise, set your project ID here."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "USd_pUT0lugr"
      },
      "outputs": [],
      "source": [
        "if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
        "    PROJECT_ID = \"[your-project-id]\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "timestamp"
      },
      "source": [
        "#### Timestamp\n",
        "\n",
        "If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "c-pX32xalugs"
      },
      "outputs": [],
      "source": [
        "from datetime import datetime\n",
        "\n",
        "TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gcp_authenticate"
      },
      "source": [
        "### Authenticate your Google Cloud account\n",
        "\n",
        "**If you are using Google Cloud Notebooks**, your environment is already\n",
        "authenticated. Skip this step.\n",
        "\n",
        "**If you are using Colab**, run the cell below and follow the instructions\n",
        "when prompted to authenticate your account via oAuth.\n",
        "\n",
        "**Otherwise**, follow these steps:\n",
        "\n",
        "1. In the Cloud Console, go to the [**Create service account key**\n",
        "   page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
        "\n",
        "2. Click **Create service account**.\n",
        "\n",
        "3. In the **Service account name** field, enter a name, and\n",
        "   click **Create**.\n",
        "\n",
        "4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
        "into the filter box, and select\n",
        "   **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
        "\n",
        "5. Click *Create*. A JSON file that contains your key downloads to your\n",
        "local environment.\n",
        "\n",
        "6. Enter the path to your service account key as the\n",
        "`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vF60K5v1lugs"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "\n",
        "# If you are running this notebook in Colab, run this cell and follow the\n",
        "# instructions to authenticate your GCP account. This provides access to your\n",
        "# Cloud Storage bucket and lets you submit training jobs and prediction\n",
        "# requests.\n",
        "\n",
        "# The Google Cloud Notebook product has specific requirements\n",
        "IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
        "\n",
        "# If on Google Cloud Notebooks, then don't execute this code\n",
        "if not IS_GOOGLE_CLOUD_NOTEBOOK:\n",
        "    if \"google.colab\" in sys.modules:\n",
        "        from google.colab import auth as google_auth\n",
        "\n",
        "        google_auth.authenticate_user()\n",
        "\n",
        "    # If you are running this notebook locally, replace the string below with the\n",
        "    # path to your service account key and run this cell to authenticate your GCP\n",
        "    # account.\n",
        "    elif not os.getenv(\"IS_TESTING\"):\n",
        "        %env GOOGLE_APPLICATION_CREDENTIALS ''"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bucket:custom"
      },
      "source": [
        "### Create a Cloud Storage bucket\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "When you submit a training job using the Cloud SDK, you upload a Python package\n",
        "containing your training code to a Cloud Storage bucket. Vertex AI runs\n",
        "the code from this package. In this tutorial, Vertex AI also saves the\n",
        "trained model that results from your job in the same bucket. Using this model artifact, you can then create Vertex AI model resources.\n",
        "\n",
        "Set the name of your Cloud Storage bucket below. It must be unique across all\n",
        "Cloud Storage buckets.\n",
        "\n",
        "You may also change the `REGION` variable, which is used for operations\n",
        "throughout the rest of this notebook. Make sure to [choose a region where Vertex AI services are\n",
        "available](https://cloud.google.com/vertex-ai/docs/general/locations#available_regions). You may\n",
        "not use a Multi-Regional Storage bucket for training with Vertex AI."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bucket"
      },
      "outputs": [],
      "source": [
        "BUCKET_NAME = \"gs://[your-bucket-name]\"  # @param {type:\"string\"}\n",
        "REGION = \"[your-region]\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_bucket"
      },
      "outputs": [],
      "source": [
        "if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n",
        "    BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "create_bucket"
      },
      "source": [
        "**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Oz8J0vmSlugt"
      },
      "outputs": [],
      "source": [
        "! gsutil mb -l $REGION $BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "validate_bucket"
      },
      "source": [
        "Finally, validate access to your Cloud Storage bucket by examining its contents:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oadE10x2lugu"
      },
      "outputs": [],
      "source": [
        "! gsutil ls -al $BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "setup_vars"
      },
      "source": [
        "### Set up variables\n",
        "\n",
        "Next, set up some variables used throughout the tutorial."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "import_aip"
      },
      "source": [
        "#### Import Vertex SDK for Python\n",
        "\n",
        "Import the Vertex SDK for Python into your Python environment and initialize it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cNEiwLd0lugu"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import sys\n",
        "\n",
        "from google.cloud import aiplatform\n",
        "from google.cloud.aiplatform import gapic as aip\n",
        "\n",
        "aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_NAME)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "accelerators:training,prediction"
      },
      "source": [
        "#### Set hardware accelerators\n",
        "\n",
        "You can set hardware accelerators for both training and prediction.\n",
        "\n",
        "Set the variables `TRAIN_GPU/TRAIN_NGPU` and `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Tesla K80 GPUs allocated to each VM, you would specify:\n",
        "\n",
        "    (aip.AcceleratorType.NVIDIA_TESLA_K80, 4)\n",
        "\n",
        "See the [locations where accelerators are available](https://cloud.google.com/vertex-ai/docs/general/locations#accelerators).\n",
        "\n",
        "Otherwise specify `(None, None)` to use a container image to run on a CPU.\n",
        "\n",
        "*Note*: TensorFlow releases earlier than 2.3 for GPU support fail to load the custom model in this tutorial. This issue is caused by static graph operations that are generated in the serving function. This is a known issue, which is fixed in TensorFlow 2.3. If you encounter this issue with your own custom models, use a container image for TensorFlow 2.3 or later with GPU support."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xd5PLXDTlugv"
      },
      "outputs": [],
      "source": [
        "TRAIN_GPU, TRAIN_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)\n",
        "\n",
        "DEPLOY_GPU, DEPLOY_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "container:training,prediction"
      },
      "source": [
        "#### Set pre-built containers\n",
        "\n",
        "Vertex AI provides pre-built containers to run training and prediction.\n",
        "\n",
        "For the latest list, see [Pre-built containers for training](https://cloud.google.com/vertex-ai/docs/training/pre-built-containers) and [Pre-built containers for prediction](https://cloud.google.com/vertex-ai/docs/predictions/pre-built-containers)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1u1mr18jlugv"
      },
      "outputs": [],
      "source": [
        "TRAIN_VERSION = \"tf-gpu.2-1\"\n",
        "DEPLOY_VERSION = \"tf2-gpu.2-1\"\n",
        "\n",
        "TRAIN_IMAGE = \"gcr.io/cloud-aiplatform/training/{}:latest\".format(TRAIN_VERSION)\n",
        "DEPLOY_IMAGE = \"gcr.io/cloud-aiplatform/prediction/{}:latest\".format(DEPLOY_VERSION)\n",
        "\n",
        "print(\"Training:\", TRAIN_IMAGE, TRAIN_GPU, TRAIN_NGPU)\n",
        "print(\"Deployment:\", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "machine:training,prediction"
      },
      "source": [
        "#### Set machine types\n",
        "\n",
        "Next, set the machine types to use for training and prediction.\n",
        "\n",
        "- Set the variables `TRAIN_COMPUTE` and `DEPLOY_COMPUTE` to configure your compute resources for training and prediction.\n",
        " - `machine type`\n",
        "     - `n1-standard`: 3.75GB of memory per vCPU\n",
        "     - `n1-highmem`: 6.5GB of memory per vCPU\n",
        "     - `n1-highcpu`: 0.9 GB of memory per vCPU\n",
        " - `vCPUs`: number of \\[2, 4, 8, 16, 32, 64, 96 \\]\n",
        "\n",
        "*Note: The following is not supported for training:*\n",
        "\n",
        " - `standard`: 2 vCPUs\n",
        " - `highcpu`: 2, 4 and 8 vCPUs\n",
        "\n",
        "*Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs*."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YAXwbqKKlugv"
      },
      "outputs": [],
      "source": [
        "MACHINE_TYPE = \"n1-standard\"\n",
        "\n",
        "VCPU = \"4\"\n",
        "TRAIN_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\n",
        "print(\"Train machine type\", TRAIN_COMPUTE)\n",
        "\n",
        "MACHINE_TYPE = \"n1-standard\"\n",
        "\n",
        "VCPU = \"4\"\n",
        "DEPLOY_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\n",
        "print(\"Deploy machine type\", DEPLOY_COMPUTE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tutorial_start:custom"
      },
      "source": [
        "# Tutorial\n",
        "\n",
        "Now you are ready to start creating your own custom-trained model with CIFAR10."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "train_custom_model"
      },
      "source": [
        "## Train a model\n",
        "\n",
        "There are two ways you can train a custom model using a container image:\n",
        "\n",
        "- **Use a Google Cloud prebuilt container**. If you use a prebuilt container, you will additionally specify a Python package to install into the container image. This Python package contains your code for training a custom model.\n",
        "\n",
        "- **Use your own custom container image**. If you use your own container, the container needs to contain your code for training a custom model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "train_custom_job_args"
      },
      "source": [
        "### Define the command args for the training script\n",
        "\n",
        "Prepare the command-line arguments to pass to your training script.\n",
        "- `args`: The command line arguments to pass to the corresponding Python module. In this example, they will be:\n",
        "  - `\"--epochs=\" + EPOCHS`: The number of epochs for training.\n",
        "  - `\"--steps=\" + STEPS`: The number of steps (batches) per epoch.\n",
        "  - `\"--distribute=\" + TRAIN_STRATEGY\"` : The training distribution strategy to use for single or distributed training.\n",
        "     - `\"single\"`: single device.\n",
        "     - `\"mirror\"`: all GPU devices on a single compute instance.\n",
        "     - `\"multi\"`: all GPU devices on all compute instances."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1npiDcUtlugw"
      },
      "outputs": [],
      "source": [
        "JOB_NAME = \"custom_job_\" + TIMESTAMP\n",
        "MODEL_DIR = \"{}/{}\".format(BUCKET_NAME, JOB_NAME)\n",
        "\n",
        "if not TRAIN_NGPU or TRAIN_NGPU < 2:\n",
        "    TRAIN_STRATEGY = \"single\"\n",
        "else:\n",
        "    TRAIN_STRATEGY = \"mirror\"\n",
        "\n",
        "EPOCHS = 20\n",
        "STEPS = 100\n",
        "\n",
        "CMDARGS = [\n",
        "    \"--epochs=\" + str(EPOCHS),\n",
        "    \"--steps=\" + str(STEPS),\n",
        "    \"--distribute=\" + TRAIN_STRATEGY,\n",
        "]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "taskpy_contents"
      },
      "source": [
        "#### Training script\n",
        "\n",
        "In the next cell, you will write the contents of the training script, `task.py`. In summary:\n",
        "\n",
        "- Get the directory where to save the model artifacts from the environment variable `AIP_MODEL_DIR`. This variable is set by the training service.\n",
        "- Loads CIFAR10 dataset from TF Datasets (tfds).\n",
        "- Builds a model using TF.Keras model API.\n",
        "- Compiles the model (`compile()`).\n",
        "- Sets a training distribution strategy according to the argument `args.distribute`.\n",
        "- Trains the model (`fit()`) with epochs and steps according to the arguments `args.epochs` and `args.steps`\n",
        "- Saves the trained model (`save(MODEL_DIR)`) to the specified model directory."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "72rUqXNFlugx"
      },
      "outputs": [],
      "source": [
        "%%writefile task.py\n",
        "# Single, Mirror and Multi-Machine Distributed Training for CIFAR-10\n",
        "\n",
        "import tensorflow_datasets as tfds\n",
        "import tensorflow as tf\n",
        "from tensorflow.python.client import device_lib\n",
        "import argparse\n",
        "import os\n",
        "import sys\n",
        "tfds.disable_progress_bar()\n",
        "\n",
        "parser = argparse.ArgumentParser()\n",
        "parser.add_argument('--lr', dest='lr',\n",
        "                    default=0.01, type=float,\n",
        "                    help='Learning rate.')\n",
        "parser.add_argument('--epochs', dest='epochs',\n",
        "                    default=10, type=int,\n",
        "                    help='Number of epochs.')\n",
        "parser.add_argument('--steps', dest='steps',\n",
        "                    default=200, type=int,\n",
        "                    help='Number of steps per epoch.')\n",
        "parser.add_argument('--distribute', dest='distribute', type=str, default='single',\n",
        "                    help='distributed training strategy')\n",
        "args = parser.parse_args()\n",
        "\n",
        "print('Python Version = {}'.format(sys.version))\n",
        "print('TensorFlow Version = {}'.format(tf.__version__))\n",
        "print('TF_CONFIG = {}'.format(os.environ.get('TF_CONFIG', 'Not found')))\n",
        "print('DEVICES', device_lib.list_local_devices())\n",
        "\n",
        "# Single Machine, single compute device\n",
        "if args.distribute == 'single':\n",
        "    if tf.test.is_gpu_available():\n",
        "        strategy = tf.distribute.OneDeviceStrategy(device=\"/gpu:0\")\n",
        "    else:\n",
        "        strategy = tf.distribute.OneDeviceStrategy(device=\"/cpu:0\")\n",
        "# Single Machine, multiple compute device\n",
        "elif args.distribute == 'mirror':\n",
        "    strategy = tf.distribute.MirroredStrategy()\n",
        "# Multiple Machine, multiple compute device\n",
        "elif args.distribute == 'multi':\n",
        "    strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()\n",
        "\n",
        "# Multi-worker configuration\n",
        "print('num_replicas_in_sync = {}'.format(strategy.num_replicas_in_sync))\n",
        "\n",
        "# Preparing dataset\n",
        "BUFFER_SIZE = 10000\n",
        "BATCH_SIZE = 64\n",
        "\n",
        "def make_datasets_unbatched():\n",
        "  # Scaling CIFAR10 data from (0, 255] to (0., 1.]\n",
        "  def scale(image, label):\n",
        "    image = tf.cast(image, tf.float32)\n",
        "    image /= 255.0\n",
        "    return image, label\n",
        "\n",
        "  datasets, info = tfds.load(name='cifar10',\n",
        "                            with_info=True,\n",
        "                            as_supervised=True)\n",
        "  return datasets['train'].map(scale).cache().shuffle(BUFFER_SIZE).repeat()\n",
        "\n",
        "\n",
        "# Build the Keras model\n",
        "def build_and_compile_cnn_model():\n",
        "  model = tf.keras.Sequential([\n",
        "      tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(32, 32, 3)),\n",
        "      tf.keras.layers.MaxPooling2D(),\n",
        "      tf.keras.layers.Conv2D(32, 3, activation='relu'),\n",
        "      tf.keras.layers.MaxPooling2D(),\n",
        "      tf.keras.layers.Flatten(),\n",
        "      tf.keras.layers.Dense(10, activation='softmax')\n",
        "  ])\n",
        "  model.compile(\n",
        "      loss=tf.keras.losses.sparse_categorical_crossentropy,\n",
        "      optimizer=tf.keras.optimizers.SGD(learning_rate=args.lr),\n",
        "      metrics=['accuracy'])\n",
        "  return model\n",
        "\n",
        "# Train the model\n",
        "NUM_WORKERS = strategy.num_replicas_in_sync\n",
        "# Here the batch size scales up by number of workers since\n",
        "# `tf.data.Dataset.batch` expects the global batch size.\n",
        "GLOBAL_BATCH_SIZE = BATCH_SIZE * NUM_WORKERS\n",
        "MODEL_DIR = os.getenv(\"AIP_MODEL_DIR\")\n",
        "\n",
        "train_dataset = make_datasets_unbatched().batch(GLOBAL_BATCH_SIZE)\n",
        "\n",
        "with strategy.scope():\n",
        "  # Creation of dataset, and model building/compiling need to be within\n",
        "  # `strategy.scope()`.\n",
        "  model = build_and_compile_cnn_model()\n",
        "\n",
        "model.fit(x=train_dataset, epochs=args.epochs, steps_per_epoch=args.steps)\n",
        "model.save(MODEL_DIR)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "train_custom_job"
      },
      "source": [
        "### Train the model\n",
        "\n",
        "Define your custom training job on Vertex AI.\n",
        "\n",
        "Use the `CustomTrainingJob` class to define the job, which takes the following parameters:\n",
        "\n",
        "- `display_name`: The user-defined name of this training pipeline.\n",
        "- `script_path`: The local path to the training script.\n",
        "- `container_uri`: The URI of the training container image.\n",
        "- `requirements`: The list of Python package dependencies of the script.\n",
        "- `model_serving_container_image_uri`: The URI of a container that can serve predictions for your model — either a prebuilt container or a custom container.\n",
        "\n",
        "Use the `run` function to start training, which takes the following parameters:\n",
        "\n",
        "- `args`: The command line arguments to be passed to the Python script.\n",
        "- `replica_count`: The number of worker replicas.\n",
        "- `model_display_name`: The display name of the `Model` if the script produces a managed `Model`.\n",
        "- `machine_type`: The type of machine to use for training.\n",
        "- `accelerator_type`: The hardware accelerator type.\n",
        "- `accelerator_count`: The number of accelerators to attach to a worker replica.\n",
        "\n",
        "The `run` function creates a training pipeline that trains and creates a `Model` object. After the training pipeline completes, the `run` function returns the `Model` object."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mxIxvDdglugx"
      },
      "outputs": [],
      "source": [
        "job = aiplatform.CustomTrainingJob(\n",
        "    display_name=JOB_NAME,\n",
        "    script_path=\"task.py\",\n",
        "    container_uri=TRAIN_IMAGE,\n",
        "    requirements=[\"tensorflow_datasets==1.3.0\"],\n",
        "    model_serving_container_image_uri=DEPLOY_IMAGE,\n",
        ")\n",
        "\n",
        "MODEL_DISPLAY_NAME = \"cifar10-\" + TIMESTAMP\n",
        "\n",
        "# Start the training\n",
        "if TRAIN_GPU:\n",
        "    model = job.run(\n",
        "        model_display_name=MODEL_DISPLAY_NAME,\n",
        "        args=CMDARGS,\n",
        "        replica_count=1,\n",
        "        machine_type=TRAIN_COMPUTE,\n",
        "        accelerator_type=TRAIN_GPU.name,\n",
        "        accelerator_count=TRAIN_NGPU,\n",
        "    )\n",
        "else:\n",
        "    model = job.run(\n",
        "        model_display_name=MODEL_DISPLAY_NAME,\n",
        "        args=CMDARGS,\n",
        "        replica_count=1,\n",
        "        machine_type=TRAIN_COMPUTE,\n",
        "        accelerator_count=0,\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "make_prediction"
      },
      "source": [
        "## Make a batch prediction request\n",
        "\n",
        "Send a batch prediction request to your deployed model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "get_test_item:test"
      },
      "source": [
        "### Get test data\n",
        "\n",
        "Download images from the CIFAR dataset and preprocess them.\n",
        "\n",
        "#### Download the test images\n",
        "\n",
        "Download the provided set of images from the CIFAR dataset:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "E1EQBPGnlugz"
      },
      "outputs": [],
      "source": [
        "# Download the images\n",
        "! gsutil -m cp -r gs://cloud-samples-data/ai-platform-unified/cifar_test_images ."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "prepare_test_item:test,image"
      },
      "source": [
        "#### Preprocess the images\n",
        "Before you can run the data through the endpoint, you need to preprocess it to match the format that your custom model defined in `task.py` expects.\n",
        "\n",
        "`x_test`:\n",
        "Normalize (rescale) the pixel data by dividing each pixel by 255. This replaces each single byte integer pixel with a 32-bit floating point number between 0 and 1.\n",
        "\n",
        "`y_test`:\n",
        "You can extract the labels from the image filenames. Each image's filename format is \"image_{LABEL}_{IMAGE_NUMBER}.jpg\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cl59KGnXlugz"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "from PIL import Image\n",
        "\n",
        "# Load image data\n",
        "IMAGE_DIRECTORY = \"cifar_test_images\"\n",
        "\n",
        "image_files = [file for file in os.listdir(IMAGE_DIRECTORY) if file.endswith(\".jpg\")]\n",
        "\n",
        "# Decode JPEG images into numpy arrays\n",
        "image_data = [\n",
        "    np.asarray(Image.open(os.path.join(IMAGE_DIRECTORY, file))) for file in image_files\n",
        "]\n",
        "\n",
        "# Scale and convert to expected format\n",
        "x_test = [(image / 255.0).astype(np.float32).tolist() for image in image_data]\n",
        "\n",
        "# Extract labels from image name\n",
        "y_test = [int(file.split(\"_\")[1]) for file in image_files]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b1e29665076f"
      },
      "source": [
        "#### Prepare data for batch prediction\n",
        "Before you can run the data through batch prediction, you need to save the data into one of a few possible formats.\n",
        "\n",
        "For this tutorial, use JSONL as it's compatible with the 3-dimensional list that each image is currently represented in. To do this:\n",
        "\n",
        "1. In a file, write each instance as JSON on its own line.\n",
        "2. Upload this file to Cloud Storage.\n",
        "\n",
        "For more details on batch prediction input formats: https://cloud.google.com/vertex-ai/docs/predictions/batch-predictions#batch_request_input"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3e6b04d29c3b"
      },
      "outputs": [],
      "source": [
        "import json\n",
        "\n",
        "BATCH_PREDICTION_INSTANCES_FILE = \"batch_prediction_instances.jsonl\"\n",
        "\n",
        "BATCH_PREDICTION_GCS_SOURCE = (\n",
        "    BUCKET_NAME + \"/batch_prediction_instances/\" + BATCH_PREDICTION_INSTANCES_FILE\n",
        ")\n",
        "\n",
        "# Write instances at JSONL\n",
        "with open(BATCH_PREDICTION_INSTANCES_FILE, \"w\") as f:\n",
        "    for x in x_test:\n",
        "        f.write(json.dumps(x) + \"\\n\")\n",
        "\n",
        "# Upload to Cloud Storage bucket\n",
        "! gsutil cp $BATCH_PREDICTION_INSTANCES_FILE $BATCH_PREDICTION_GCS_SOURCE\n",
        "\n",
        "print(\"Uploaded instances to: \", BATCH_PREDICTION_GCS_SOURCE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "send_prediction_request:image"
      },
      "source": [
        "### Send the prediction request\n",
        "\n",
        "To make a batch prediction request, call the model object's `batch_predict` method with the following parameters: \n",
        "- `instances_format`: The format of the batch prediction request file: \"jsonl\", \"csv\", \"bigquery\", \"tf-record\", \"tf-record-gzip\" or \"file-list\"\n",
        "- `prediction_format`: The format of the batch prediction response file: \"jsonl\", \"csv\", \"bigquery\", \"tf-record\", \"tf-record-gzip\" or \"file-list\"\n",
        "- `job_display_name`: The human readable name for the prediction job.\n",
        " - `gcs_source`: A list of one or more Cloud Storage paths to your batch prediction requests.\n",
        "- `gcs_destination_prefix`: The Cloud Storage path that the service will write the predictions to.\n",
        "- `model_parameters`: Additional filtering parameters for serving prediction results.\n",
        "- `machine_type`: The type of machine to use for training.\n",
        "- `accelerator_type`: The hardware accelerator type.\n",
        "- `accelerator_count`: The number of accelerators to attach to a worker replica.\n",
        "- `starting_replica_count`: The number of compute instances to initially provision.\n",
        "- `max_replica_count`: The maximum number of compute instances to scale to. In this tutorial, only one instance is provisioned.\n",
        "\n",
        "### Compute instance scaling\n",
        "\n",
        "You can specify a single instance (or node) to process your batch prediction request. This tutorial uses a single node, so the variables `MIN_NODES` and `MAX_NODES` are both set to `1`.\n",
        "\n",
        "If you want to use multiple nodes to process your batch prediction request, set `MAX_NODES` to the maximum number of nodes you want to use. Vertex AI autoscales the number of nodes used to serve your predictions, up to the maximum number you set. Refer to the [pricing page](https://cloud.google.com/vertex-ai/pricing#prediction-prices) to understand the costs of autoscaling with multiple nodes.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1cf1076178fc"
      },
      "outputs": [],
      "source": [
        "MIN_NODES = 1\n",
        "MAX_NODES = 1\n",
        "\n",
        "# The name of the job\n",
        "BATCH_PREDICTION_JOB_NAME = \"cifar10_batch-\" + TIMESTAMP\n",
        "\n",
        "# Folder in the bucket to write results to\n",
        "DESTINATION_FOLDER = \"batch_prediction_results\"\n",
        "\n",
        "# The Cloud Storage bucket to upload results to\n",
        "BATCH_PREDICTION_GCS_DEST_PREFIX = BUCKET_NAME + \"/\" + DESTINATION_FOLDER\n",
        "\n",
        "# Make SDK batch_predict method call\n",
        "batch_prediction_job = model.batch_predict(\n",
        "    instances_format=\"jsonl\",\n",
        "    predictions_format=\"jsonl\",\n",
        "    job_display_name=BATCH_PREDICTION_JOB_NAME,\n",
        "    gcs_source=BATCH_PREDICTION_GCS_SOURCE,\n",
        "    gcs_destination_prefix=BATCH_PREDICTION_GCS_DEST_PREFIX,\n",
        "    model_parameters=None,\n",
        "    machine_type=DEPLOY_COMPUTE,\n",
        "    accelerator_type=DEPLOY_GPU,\n",
        "    accelerator_count=DEPLOY_NGPU,\n",
        "    starting_replica_count=MIN_NODES,\n",
        "    max_replica_count=MAX_NODES,\n",
        "    sync=True,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "df3b3d1bdd24"
      },
      "source": [
        "### Retrieve batch prediction results\n",
        "When the batch prediction is done processing, you can finally view the predictions stored at the Cloud Storage path you set as output. The predictions will be in a JSONL format, which you indicated when you created the batch prediction job. The predictions are located in a subdirectory starting with the name prediction. Within that directory, there is a file named prediction.results-xxxx-of-xxxx.\n",
        "\n",
        "Let's display the contents. You will get a row for each prediction. The row is the softmax probability distribution for the corresponding CIFAR10 classes."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2f10b13b2b88"
      },
      "outputs": [],
      "source": [
        "RESULTS_DIRECTORY = \"prediction_results\"\n",
        "RESULTS_DIRECTORY_FULL = RESULTS_DIRECTORY + \"/\" + DESTINATION_FOLDER\n",
        "\n",
        "# Create missing directories\n",
        "os.makedirs(RESULTS_DIRECTORY, exist_ok=True)\n",
        "\n",
        "# Get the Cloud Storage paths for each result\n",
        "! gsutil -m cp -r $BATCH_PREDICTION_GCS_DEST_PREFIX $RESULTS_DIRECTORY\n",
        "\n",
        "# Get most recently modified directory\n",
        "latest_directory = max(\n",
        "    [\n",
        "        os.path.join(RESULTS_DIRECTORY_FULL, d)\n",
        "        for d in os.listdir(RESULTS_DIRECTORY_FULL)\n",
        "    ],\n",
        "    key=os.path.getmtime,\n",
        ")\n",
        "\n",
        "# Get downloaded results in directory\n",
        "results_files = []\n",
        "for dirpath, subdirs, files in os.walk(latest_directory):\n",
        "    for file in files:\n",
        "        if file.startswith(\"prediction.results\"):\n",
        "            results_files.append(os.path.join(dirpath, file))\n",
        "\n",
        "# Consolidate all the results into a list\n",
        "results = []\n",
        "for results_file in results_files:\n",
        "    # Download each result\n",
        "    with open(results_file, \"r\") as file:\n",
        "        results.extend([json.loads(line) for line in file.readlines()])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "962b5a11fdae"
      },
      "source": [
        "### Evaluate results\n",
        "\n",
        "You can then run a quick evaluation on the prediction results:\n",
        "\n",
        "1. `np.argmax`: Convert each list of confidence levels to a label\n",
        "2. Compare the predicted labels to the actual labels\n",
        "3. Calculate `accuracy` as `correct/total`\n",
        "\n",
        "To improve the accuracy, try training for a higher number of epochs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UywuX7fRlugz"
      },
      "outputs": [],
      "source": [
        "y_predicted = [np.argmax(result[\"prediction\"]) for result in results]\n",
        "\n",
        "correct = sum(y_predicted == np.array(y_test))\n",
        "accuracy = len(y_predicted)\n",
        "print(\n",
        "    f\"Correct predictions = {correct}, Total predictions = {accuracy}, Accuracy = {correct/accuracy}\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cleanup:custom"
      },
      "source": [
        "# Cleaning up\n",
        "\n",
        "To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
        "\n",
        "Otherwise, you can delete the individual resources you created in this tutorial:\n",
        "\n",
        "- Training Job\n",
        "- Model\n",
        "- Cloud Storage Bucket"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NNmebHf7lug0"
      },
      "outputs": [],
      "source": [
        "delete_training_job = True\n",
        "delete_model = True\n",
        "\n",
        "# Warning: Setting this to true will delete everything in your bucket\n",
        "delete_bucket = False\n",
        "\n",
        "# Delete the training job\n",
        "job.delete()\n",
        "\n",
        "# Delete the model\n",
        "model.delete()\n",
        "\n",
        "if delete_bucket and \"BUCKET_NAME\" in globals():\n",
        "    ! gsutil -m rm -r $BUCKET_NAME"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "sdk-custom-image-classification-batch.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
